﻿using System;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace WebApp.Extensions
{
    public static class UrlExtensions
    {
        public static string Action<TController>(this UrlHelper urlHelper, Expression<Func<TController, object>> expression)
        {
            return Action(urlHelper, expression, null);
        }

        public static string Action<TController>(this UrlHelper urlHelper, Expression<Func<TController, object>> expression, object routeValues)
        {
            var routeValueDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(routeValues);
            return Action(urlHelper, expression, routeValueDictionary);
        }

        public static string Action<TController>(this UrlHelper urlHelper, Expression<Func<TController, object>> expression, RouteValueDictionary routeValueDictionary)
        {
            routeValueDictionary = routeValueDictionary ?? new RouteValueDictionary();

            var pickerContext = urlHelper.RequestContext.HttpContext.Request.Params["pickerContext"];
            if (pickerContext != null && !routeValueDictionary.ContainsKey("pickerContext"))
            {
                routeValueDictionary.Add("pickerContext", pickerContext);
            }

            var actionName = expression.GetActionName();
            var controllerName = typeof(TController).GetControllerName();

            return urlHelper.Action(actionName, controllerName, routeValueDictionary);
        }

        public static string ToScriptSafeLink(this string xhtmlUrl)
        {
            return !string.IsNullOrEmpty(xhtmlUrl) ? xhtmlUrl.Replace("&amp;", "&") : string.Empty;
        }

        public static string GetBaseUrl(this UrlHelper urlHelper, HttpRequestBase request)
        {
            return string.Format("{0}://{1}", request.Url.Scheme, request.Url.Authority);
        }
    }
}